﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAppPlanProduccion.ServiceReference.AuthApi;
using WebAppPlanProduccion.Code;
using System.Configuration;
using Web.Framework.Config;
using Web.Framework;

namespace WebAppPlanProduccion.Account
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SiteMaster masterPage = (SiteMaster)this.Master;
                masterPage.MakeMenuVisible(false);

                LoginUser.Authenticate += new AuthenticateEventHandler(LoginUser_Authenticate);

                ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");

                BaseWebPage.ApplicationId = configuration.ApplicationId;

                var ctrl = (DropDownList)this.LoginUser.FindControl("CompanyCbo");
                ctrl.DataSource = WebServiceHelper.GetCompanies(BaseWebPage.ApplicationId);
                ctrl.DataValueField = "Id";
                ctrl.DataTextField = "Name";
                ctrl.DataBind();

                if (!this.IsPostBack)
                {
                    List<string> cookieCompany = HttpHelper.GetCookieValues(MiscClass.CookieCompany, this.Request);
                    if (cookieCompany.Count > 0)
                    {
                        ctrl.SelectedValue = cookieCompany[0];
                        this.hidCompany.Value = cookieCompany[0];
                    }
                }
                else
                {
                    ctrl.SelectedValue = this.hidCompany.Value;
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
        {
            try
            {
                int applicationId = BaseWebPage.ApplicationId;
                int companyId = 0;
                bool isAdmin = false;

                var ctrl = (DropDownList)this.LoginUser.FindControl("CompanyCbo");
                ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");

                if (LoginUser.UserName == configuration.SuperAdminName && LoginUser.Password == configuration.SuperAdminPassword)
                {
                    e.Authenticated = true;
                    companyId = Convert.ToInt32(ctrl.SelectedValue);
                    isAdmin = true;
                }
                else if (e.Authenticated = WebServiceHelper.Authenticate(BaseWebPage.ApplicationId, Convert.ToInt32(ctrl.SelectedValue), LoginUser.UserName, LoginUser.Password))
                {
                    companyId = Convert.ToInt32(ctrl.SelectedValue);
                    isAdmin = false;
                }

                if (e.Authenticated)
                {
                    //Session.Clear();
                    BaseWebPage.CompanyId = companyId;
                    BaseWebPage.IsAdmin = isAdmin;
                    BaseWebPage.ApplicationId = applicationId;
                    
                    // seteo el nombre del usuario en el login
                    string displayName = LoginUser.UserName;
                                        
                    // TODO: Habilitar con la nueva API
                    //var adUser = WebServiceHelper.GetUsers(BaseWebPage.ApplicationId, BaseWebPage.CompanyId, LoginUser.UserName).SingleOrDefault();
                    //if (adUser != null)
                    //{
                    //    if (!String.IsNullOrEmpty(adUser.GivenName))
                    //    {
                    //        displayName = adUser.GivenName;
                    //    }
                    //}

                    BaseWebPage.DisplayUserName = displayName;

                    HttpHelper.SetCookieValues(MiscClass.CookieCompany, this.Response, ctrl.SelectedValue, ctrl.SelectedItem.Text);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}
